package com.lhj.springboot3.boot313security.configuration;

import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;

/**
 * @Description
 * @Author lhj
 * @Date 2024/7/7 16:03
 */
//开启方法授权
@EnableMethodSecurity
@Configuration
public class AppSecurityConfiguration {

    @Bean
    SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests((requests) -> {
            requests.requestMatchers("/").permitAll()
                    .anyRequest().authenticated();
        });
        
        http.formLogin((from) -> from.loginPage("/login").permitAll());
//        http.formLogin((form) -> form.loginPage())
        
//        http.formLogin();
        return http.build();
    }
    
    @Bean
    UserDetailsService userDetailsService(BCryptPasswordEncoder cryptPasswordEncoder) {
        UserDetails zhangsan = User.withUsername("zhangsan")
                .password(cryptPasswordEncoder.encode("123"))
                .roles("admin", "hr")
                .authorities("file_read", "file_write")
                .build();
        
        UserDetails lisi = User.withUsername("lisi")
                .password(cryptPasswordEncoder.encode("123"))
                .roles("admin")
                .authorities("file_read")
                .build();

        UserDetails wangwu = User.withUsername("wangwu")
                .password(cryptPasswordEncoder.encode("123"))
                .roles("hr")
                .authorities("file_exec")
                .build();
        return new InMemoryUserDetailsManager(zhangsan, lisi, wangwu);
    }
    
    @Bean
    BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

}
